// 论坛帖子
// by indraw 2013.03.01
package bbs

import (
	"time"
    "strconv"
    "utils/web"
    "utils/util"

)

/**
 * 发帖回复
 *
 * author: indraw
 * date: 2013-03-01
 */
func PostReply(ctx *web.Context) string {

	//初始化
	initApp(ctx)

	SessUserID,_ := session.Get("userid")
	if SessUserID == ""{
		return tpl.Success("请您登录后发表文章")

	}
	//执行操作
    if ctx.Params["act"] == "do"{
        //板块信息
		thread := newThread()
		thread.setTid(ctx.Params["tid"])
		if err := thread.get(); err != nil {
			return tpl.Error(err.Error())
		}
        if(thread.getFid() != ctx.Params["fid"]){
            return tpl.Error("板块ID错误！")

        }
        
        //发表操作
        post := newPost()
        post.setFid(ctx.Params["fid"])
        post.setTid(ctx.Params["tid"])
		post.setContent(ctx.Params["elm1"])
		post.setSubject("回复：" + thread.Subject)

		post.setUsesig(ctx.Params["usesig"])

	    SessUserID,_ := session.Get("userid")
	    SessUserName,_ := session.Get("username")
        post.setUserid(SessUserID)
        post.setUsername(SessUserName)
		post.Useip = util.GetUserIP(ctx.Request)
		if err := post.add(); err != nil {
			return tpl.Error(err.Error())
		}
        //修改板块最后发表和主题数量
        forum := newForum()
        forum.setFid(thread.getFid())
        forum.Lastpost["userid"] = SessUserID
        forum.Lastpost["username"] = SessUserName
        forum.Lastpost["subject"] = "回复：" + thread.Subject
        forum.Lastpost["tid"] = ctx.Params["tid"]
        forum.Lastpost["time"] = strconv.FormatInt(time.Now().Unix(),10)
		if err := forum.updateLastpost(1); err != nil {
			return tpl.Error(err.Error())
		}
        
        //更新最后回复
        thread.setLastuserid(SessUserID)
        thread.Lastusername = SessUserName
		if err := thread.updateLastpost(); err != nil {
			return tpl.Error(err.Error())
		}
        //
        user := newUser()
        user.setUserid(SessUserID)
        user.Lastpost = "回复：" + thread.Subject
		if err := user.updatePost(1); err != nil {
			return tpl.Error(err.Error())
		}

        tpl.Assign("Fid", ctx.Params["fid"])
        tpl.Assign("Tid", ctx.Params["tid"])
        tpl.Assign("Message", "回复成功！")

        return tpl.Display("success_post.html")
		//return tpl.Success("回复成功")

    }
    
    return tpl.Success("功能开发中！")

}
